<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        #box{
            height:100px;
            width:100px;
            background-color: blueviolet;
            position: fixed;
            left:0;
            top:0;
        }
        #boxtwo{
            height:200px;
            width:200px;
            background-color: pink;
            position: fixed;
            left:0;
            top:200px;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <div id="boxtwo"></div>
    <script>
        let html=document.documentElement||document.body;
        function down(e){
            //初始坐标
            this.startX=e.offsetX;
            this.startY=e.offsetY;

            //最大移动范围
            this.maxW=html.clientWidth-this.offsetWidth;
            this.maxH=html.clientHeight-this.offsetHeight;
        
            //1.修改this指向 call apply--会执行函数 bind--不会执行函数
            this._move=move.bind(this);//修改this后的新函数给了addEventListener
            this._up=up.bind(this);

            window.addEventListener("mousemove",this._move)
            window.addEventListener("mouseup",this._up)
        }
        box.addEventListener("mousedown",down);
        boxtwo.addEventListener("mousedown",down);

        //把修改函数this的结果，挂载到元素上，move不受影响
        function move(e){
            //console.log(this);//this-->window
            //结束坐标
            this.endX=e.clientX;
            this.endY=e.clientY;

            //结果值
            this.resX=this.endX-this.startX;
            this.resY=this.endY-this.startY;

            //设置范围，不能超出
            this.resX=this.resX<0?0:(this.resX>this.maxW?this.maxW:this.resX);
            this.resY=this.resY<0?0:(this.resY>this.maxH?this.maxH:this.resY);

            this.style.left=this.resX+"px";
            this.style.top=this.resY+"px";
        }
        function up(){
            window.removeEventListener("mousemove",this._move)
            window.removeEventListener("mouseup",this._up)
        }
    </script>
</body>
</html>